package com.itqian.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itqian.common.exception.Assert;
import com.itqian.common.exception.ResponseEnum;
import com.itqian.common.utils.ResultVOUtil;
import com.itqian.common.vo.ResultVO;
import com.itqian.seller.entity.StoreInfo;
import com.itqian.seller.service.StoreInfoService;
import com.itqian.system.entity.Constants;
import com.itqian.system.entity.User;
import com.itqian.system.form.AddUserForm;
import com.itqian.system.service.UserService;
import com.itqian.system.vo.AdminUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jws.soap.SOAPBinding;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * @author shishuqian
 * date 2022/3/23
 * time 22:53
 **/
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private StoreInfoService storeInfoService;

    /**
     *  分页查看所有用户
     */
    @GetMapping("/userList/{page}/{size}")
    public ResultVO list(@PathVariable Integer page,@PathVariable Integer size){
        //参数非空校验
        Assert.notNull(page, ResponseEnum.PAGE_NOTNULL);
        Assert.notNull(size,ResponseEnum.SIZE_NOTNULL);

        Map<String, Object> map = userService.userList(page, size);

        return ResultVOUtil.success(map);
    }

    /**
     *
     * @author shishuqian
     * @desc  按id，或username或phone查找用户信息
     */
    @GetMapping("/getUser/{type}/{query}")
    public ResultVO getUser(@PathVariable String type,@PathVariable String query){
        //参数非空校验
        Assert.notBlank(type,ResponseEnum.PARAM_NOTNULL);
        Assert.notBlank(query,ResponseEnum.PARAM_NOTNULL);

        User user = null;
        //List<User> list = null;
        if ("userId".equals(type)){ //按id查找
            int id = Integer.parseInt(query);
            user = userService.getById(id);

        }else if ("username".equals(type)){ //按用户名查找
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username",query);
            user = userService.getOne(wrapper);
            //wrapper.like("username",query);
            //list = userService.list(wrapper);
        }else{ //按手机号查找
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",query);
            user = userService.getOne(wrapper);
            //wrapper.like("phone",query);
            //list = userService.list(wrapper);
    }


        if (user == null){
            return ResultVOUtil.fail("没有找到对应数据...");
        }
        AdminUserVO vo = new AdminUserVO();
        BeanUtils.copyProperties(user,vo);
        return ResultVOUtil.success(vo);
        //AdminUserVO vo = new AdminUserVO();
        //BeanUtils.copyProperties(user,vo);
        //return ResultVOUtil.success(vo);
    }

    /**
     *  添加用户
     */
    @PostMapping("/addUser")
    public ResultVO addUser(@Valid @RequestBody AddUserForm form){
        //判断AddUserForm中的role是否合法
        HashSet<String> set = new HashSet<>();
        set.add("user");set.add("seller");set.add("runner");
        if (!set.contains(form.getRole())){
            return ResultVOUtil.fail("添加拥护的身份类型不合法，请重试...");
        }

        //添加用户
        Integer userId = userService.addUser(form);

        //如果添加的是seller，还要为其创建默认店铺
        if (form.getRole().equals(Constants.SELLER)){
            boolean b = storeInfoService.addDefaultStore(userId);
        }

        return ResultVOUtil.success(null);

    }

    /**
     * 删除用户
     */
    @DeleteMapping("/deleteUser/{userId}")
    public ResultVO deleteUser(@PathVariable Integer userId){
        //参数非空校验
        Assert.notNull(userId, ResponseEnum.PARAM_NOTNULL);

        boolean b = userService.removeById(userId);
        if (!b){
            return ResultVOUtil.fail("删除用户失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }

    /**
     *   权限管理(更改权限)
     */
    @PutMapping("/editRole/{userId}/{role}")
    public ResultVO editRole(@PathVariable Integer userId,@PathVariable String role){
        //参数非空校验
        Assert.notNull(userId,ResponseEnum.PARAM_NOTNULL);
        Assert.notBlank(role,ResponseEnum.PARAM_NOTNULL);
        //校验前端传来的身份权限字段是否合法
        HashSet<String> set = new HashSet<>();
        set.add("user");set.add("seller");set.add("runner");set.add("admin");
        List<String> list = Arrays.asList(role.split("_"));
        if (!set.containsAll(list)){
            return ResultVOUtil.fail("权限参数不合法，请重试...");
        }
        //把传入的身份权限列表放入set中，主要是为了去重
        HashSet<String> roleSet = new HashSet<>(list);
        //每个用户都有user权限
        roleSet.add("user");
        //修改权限
        boolean b = userService.editRole(userId, roleSet);
        //如果身份权限中包含seller，还要判断是否要为用户创建店铺
        if (roleSet.contains(Constants.SELLER)){
            QueryWrapper<StoreInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("seller_id",userId);
            StoreInfo one = storeInfoService.getOne(wrapper);
            if (one == null){
                boolean b1 = storeInfoService.addDefaultStore(userId);
            }
        }
        return ResultVOUtil.success(null);
    }

    /**
     *  用户钱包充值
     */
    @PutMapping("/addMoney/{userId}/{amount}")
    public ResultVO addMoney(@PathVariable Integer userId,@PathVariable BigDecimal amount){
        //参数非空校验
        Assert.notNull(userId,ResponseEnum.PARAM_NOTNULL);
        Assert.notNull(amount,ResponseEnum.PARAM_NOTNULL);

        User user = userService.getById(userId);
        BigDecimal nowMoney = user.getMoney();
        nowMoney = nowMoney.add(amount);
        user.setMoney(nowMoney);
        boolean b = userService.updateById(user);
        if (!b){
            return ResultVOUtil.fail("充值失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }

    /**
     *  用户钱包退款
     */
    @PutMapping("/subMoney/{userId}/{amount}")
    public ResultVO subMoney(@PathVariable Integer userId,@PathVariable BigDecimal amount){
        //参数非空校验
        Assert.notNull(userId,ResponseEnum.PARAM_NOTNULL);
        Assert.notNull(amount,ResponseEnum.PARAM_NOTNULL);

        User user = userService.getById(userId);
        BigDecimal nowMoney = user.getMoney();
        nowMoney = nowMoney.subtract(amount);
        //判断此时余额是否小于0
        if (nowMoney.compareTo(BigDecimal.ZERO) == -1){
            return ResultVOUtil.fail("退款失败，退款数目大于钱包余额...");
        }
        user.setMoney(nowMoney);
        boolean b = userService.updateById(user);
        if (!b){
            return ResultVOUtil.fail("退款失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }



}
